<?php
namespace app\admin\controller;
use think\Cookie;
class Client extends Common
{
    /*客户列表*/
    public function lst(){
        $aid = session('uid','','admin');
        $keywords = input('keywords');
        $group_id=db('admin')->where('id',$aid)->value('group_id');
        if($group_id == 1){
            if($keywords){
                $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status','<>','0')->where('c.name|c.activity|c.phone|c.wx|a.name','like',"%".$keywords."%")->order('c.id desc')->paginate(10);
                $count=db('client')->where('status','<>','0')->where('name|activity|phone|wx','like',"%".$keywords."%")->count();
            }else{
                $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status','<>','0')->order('c.id desc')->paginate(10);
                $count=db('client')->where('status','<>','0')->count();
            }
        }else{
            $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status','<>','0')->where('c.xaid',$aid);
            $count=db('client')->where('status','<>','0')->where('xaid',$aid);
            if($keywords)
            {
                $clientRes = $clientRes->where('c.name|c.activity|c.phone|c.wx|a.name','like',"%".$keywords."%");
                $count = $count->where('name|activity|phone|wx','like',"%".$keywords."%");
            }
            $clientRes = $clientRes->order('c.id desc')->paginate(10);
            $count = $count->count();
        }
        $clientRes = $this->getNewList($clientRes);
        $this->assign([
            'clientRes'=>$clientRes,
            'count'=>$count,
            'lst'=>'lst'
        ]);
        return view();
    }
    /*洽谈中*/
    public function lst4(){
        $aid = session('uid','','admin');
        $keywords = input('keywords');
        $group_id=db('admin')->where('id',$aid)->value('group_id');
        $config['query'] = ['keywords'=>$keywords,'only_my'=>$onlyMy];
        if($group_id == 1){
            if($keywords){
                $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status',1)->where('c.name|c.activity|c.phone|c.wx|a.name','like',"%".$keywords."%")->order('c.id desc')->paginate(10,false,$config);
                $count=db('client')->where('status','<>','0')->where('name|activity|phone|wx','like',"%".$keywords."%")->count();
            }else{
                $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status',1)->order('c.id desc')->paginate(10,false,$config);
                $count=db('client')->where('status','<>','0')->count();
            }
        }else{
            $clientRes=db('client')->alias('c')->field('c.*')->where('c.status','IN','0,1')->where('c.xaid|aid',$aid);
            $count=db('client')->where('status','IN','0,1')->where('xaid|aid',$aid);
            if($keywords)
            {
                $clientRes = $clientRes->where('c.name|c.activity|c.phone|c.wx','like',"%".$keywords."%");
                $count = $count->where('name|activity|phone|wx','like',"%".$keywords."%");
            }
            $clientRes = $clientRes->order('c.id desc')->paginate(10);
            $count = $count->count();
        }
        $this->assign([
            'clientRes'=>$clientRes,
            'count'=>$count,
            'lst'=>'lst4',
            'status'=>1
        ]);
        return view('lst');
    }

    /*保A客户*/
    public function lst2(){
        $aid = session('uid','','admin');
        $keywords = input('keywords');
        $userInfo=db('admin')->where('id',$aid)->find();
        $group_id = $userInfo['group_id'];
        $groupMembers = $userInfo['group_members'];
        $onlyMy = input('only_my')?input('only_my'):0;
        $config['query'] = ['keywords'=>$keywords,'only_my'=>$onlyMy];
        if($group_id == 1){
            if($keywords){
                $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status',3)->where('c.name|c.activity|c.phone|c.wx|a.name','like',"%".$keywords."%")->order('c.id desc')->paginate(10,false,$config);
                $count=db('client')->where('status','<>','0')->where('name|activity|phone|wx','like',"%".$keywords."%")->count();
            }else{
                $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status',3)->order('c.id desc')->paginate(10,false,$config);
                $count=db('client')->where('status','<>','0')->count();
            }
        }else{
            $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status',3);
            $count=db('client')->where('status','3');
            $groupMembers = $groupMembers?$groupMembers.','.$aid:$aid;
            if($group_id == 5)
            {
                $clientRes=$clientRes->where('c.xaid','IN',$groupMembers);
                $count=$count->where('xaid','IN',$groupMembers);
            }
            else
            {
                $clientRes=$clientRes->where('c.xaid',$aid);
                $count=$count->where('xaid',$aid);
            }
            if($keywords)
            {
                $clientRes=$clientRes->where('c.name|c.activity|c.phone|c.wx|a.name','like',"%".$keywords."%");
                $count=$count->where('name|activity|phone|wx','like',"%".$keywords."%");
            }
            if($onlyMy)
            {
                $clientRes=$clientRes->where('c.xaid',$aid);
                $count=$count->where('xaid',$aid);
            }
            //GROUP_CONCAT(union_id SEPARATOR ',')
            $baoa3List = db('client')->field('union_id,count(union_id) as count')->where('status',3)->group('union_id having count>2')->select();
            
            if($baoa3List[0]['union_id'])
            {
                foreach ($baoa3List as $k => $v) {
                    $unionIds[] = $v['union_id'];
                }
                $clientRes=$clientRes->whereOr('union_id','IN',implode(',', $unionIds));
            }



            $count=$count->count();
            $clientRes=$clientRes->order('c.id desc')->paginate(10,false,$config);
        }
        $clientRes = $this->getNewList($clientRes);
        $this->assign([
            'clientRes'=>$clientRes,
            'count'=>$count,
            'lst'=>'lst2',
            'status'=>3
        ]);
        return view('lst');
    }
    /*保A客户*/
    public function lst3(){
//        echo "<pre>";
//        print_r('lst3');
//        die;
//        tp_client
//        $arr = db('client')->field('id')->where('xaid',23)->where('status',4)->select();
//        $str = '';
//        foreach($arr as $key => $val){
//            $str .= $val['id'] . ',';
//        }
//        $str = trim($str,',');
//
//        $data = ['xaid' => 27];
//        $re = db('client')->where('id','in',$str)->update($data);
//
//        echo "<pre>";
//        var_dump($re);
//        die;

        $aid = session('uid','','admin');
        $keywords = input('keywords');
        $admin_id = input('admin_id');
        $userInfo=db('admin')->where('id',$aid)->find();
        $group_id = $userInfo['group_id'];
        $groupMembers = $userInfo['group_members'];
        $isRevoke = input('is_revoke')?input('is_revoke'):0;
        $onlyMy = input('only_my')?input('only_my'):0;
        $startDate = input()['start_date'];
        $endDate = input()['end_date'];
        
        $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status',4)->where('c.is_revoke',$isRevoke);
        $count=db('client')->where('status',4)->where('is_revoke',$isRevoke);
        $groupMembers = $groupMembers?$groupMembers.','.$aid:$aid;
        if($group_id == 5)
        {
            //$clientRes=$clientRes->where('c.xaid','IN',$groupMembers);
            //$count=$count->where('xaid','IN',$groupMembers);
        }
        else
        {
            //$clientRes=$clientRes->where('c.xaid',$aid);
            //$count=$count->where('xaid',$aid);
        }
        if($keywords)
        {
            $clientRes=$clientRes->where('c.name|c.activity|c.phone|c.wx|a.name','like',"%".$keywords."%");
            $count=$count->where('name|activity|phone|wx','like',"%".$keywords."%");
        }
        if($onlyMy)
        {
            $clientRes=$clientRes->where('c.xaid',$aid);
            $count=$count->where('xaid',$aid);
        }
        if($admin_id)
        {
            $admin_id = (int)$admin_id;

            $clientRes=$clientRes->where('c.xaid',$admin_id);
            $count=$count->where('xaid',$admin_id);
        }
        if($startDate )
        {
            $clientRes=$clientRes->where('qiandan_time','>=',strtotime($startDate));
            $count=$count->where('qiandan_time','>=',strtotime($startDate));
        }
        
        if($endDate )
        {
            $clientRes=$clientRes->where('qiandan_time','<',(strtotime($endDate)+86400));
            $count=$count->where('qiandan_time','<',(strtotime($endDate)+86400));
        }
        $count=$count->count();
        $clientRes=$clientRes->order('c.qiandan_time desc')->paginate(10,false,['query'=>$this->request->param()]);

        $clientRes = $this->getNewList($clientRes);

        if(request()->isAjax()) {
            $post = input('post.');
            $department_id = $post['department_id'];

            $admin_list = Db('admin')->where('group_id','in','2,5')->where('department_id',$department_id)->select();

            return ['msg'=>'成功','icon'=>1,'apply'=>1,'data'=>$admin_list];
        }

        $this->assign([
            'clientRes'=>$clientRes,
            'count'=>$count,
            'lst'=>'lst3',
            'status'=>4
        ]);
        return view('lst');
    }
    
    /*客户池*/
    public function ci_lst(){
        $aid = session('uid','','admin');
        $keywords = input('keywords');
        $onlyMy = input('only_my');
        $isGroup = input('is_group');
        $config = ['query' => request()->param()];
        $clientRes = db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.aid')->where('c.status','0');
        $count = db('client')->where('status','0');
        if($keywords)
        {
            $clientRes = $clientRes->where('c.name|c.activity|c.phone|c.wx','like',"%".$keywords."%");
            $count = $count->where('name|activity|phone|wx','like',"%".$keywords."%");
        }
        if($onlyMy)
        {
            $clientRes = $clientRes->where('c.aid',$aid);
            $count = $count->where('aid',$aid);
        }
        if($isGroup)
        {
            $groupMembers = db('admin')->where("FIND_IN_SET({$aid},group_members)")->value('group_members');
            $clientRes = $clientRes->where('group_time' ,'>', time()-7*86400)->where('group_admin_id','IN',$groupMembers);
        }
        else if($onlyMy != 1)
        {
            $clientRes = $clientRes->where('group_time' ,'<', time()-7*86400);
        }
        $clientRes = $clientRes->order('c.id desc')->paginate(10,false,$config);
        $count = $count->count();
        $this->assign([
            'clientRes'=>$clientRes,
            'count'=>$count,
            'lst'=>'ci_lst'
        ]);
        return view();
    }
    
    public function export()
    {
        $status = input('status');
        require_once('../extend/PHPExcel/Classes/PHPExcel.php');
        require_once('../extend/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php');

        $aid = session('uid','','admin');
        $userInfo=db('admin')->where('id',$aid)->find();
        $group_id = $userInfo['group_id'];
        $groupMembers = $userInfo['group_members'];
        
        $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.aid'); 
        $clientRes=$clientRes->where('c.xaid = 0')->order('c.id desc')->cache(true)->limit(50000,50000)->select();//
        $clientRes = (object)$clientRes;
    //  print_r($clientRes);exit;
        $objPHPExcel = new \PHPExcel();
        $find_sheet_title = '客户数据';
        $objPHPExcel->getActiveSheet()->setCellValue('A1', $find_sheet_title);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '业务员')->setCellValue('B1', '客户姓名')->setCellValue('C1', '电话')->setCellValue('D1', '微信')->setCellValue('E1', '微信码')->setCellValue('F1', '地区')->setCellValue('G1', '活动名称')->setCellValue('H1', '状态')->setCellValue('I1', '录入时间')->setCellValue('J1', '签单时间')->setCellValue('K1', '签单公司')->setCellValue('L1', '直播需求')->setCellValue('M1', '手续费')->setCellValue('N1', '
    分成比例');
        $srow = [1=>'录入',2=>'洽谈',3=>'保A',4=>'签单',0=>'客户池'];
        
        //设置居中
        $objPHPExcel->getActiveSheet()->getStyle('A1:I1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A:I')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(25);
        //写入到第一个sheet
        $k = 1;
        foreach ($clientRes as $v){
            $k = $k+1;
            $v = (object)$v;
            $objPHPExcel->getactivesheet()->setcellvalue('A'.$k, $v->aname);
            $objPHPExcel->getactivesheet()->setcellvalue('B'.$k, $v->name);
            $objPHPExcel->getactivesheet()->setcellvalue('C'.$k, $v->phone);
            $objPHPExcel->getactivesheet()->setcellvalue('D'.$k, $v->wx);
            $objPHPExcel->getactivesheet()->setcellvalue('E'.$k, $v->wx_code?'http://oa.tovqb.top/'.$v->wx_code:''  );
            $objPHPExcel->getactivesheet()->setcellvalue('F'.$k, $v->address);
            $objPHPExcel->getactivesheet()->setcellvalue('G'.$k, $v->activity);
            $objPHPExcel->getactivesheet()->setcellvalue('H'.$k, $srow[$v->status]);
            $objPHPExcel->getactivesheet()->setcellvalue('I'.$k, date('Y-m-d H:i:s',$v->add_time) );
            $objPHPExcel->getactivesheet()->setcellvalue('J'.$k, $v->qiandan_time?date('Y-m-d H:i:s',$v->qiandan_time):'' );
            $objPHPExcel->getactivesheet()->setcellvalue('K'.$k, $v->company_name);
            $objPHPExcel->getactivesheet()->setcellvalue('L'.$k, $v->company_address);
            $objPHPExcel->getactivesheet()->setcellvalue('M'.$k, $v->cashing_fee);
            $objPHPExcel->getactivesheet()->setcellvalue('N'.$k, $v->radio);
            
        }
        /*保存到第一个sheet*/
        $objPHPExcel->getActiveSheet()->setTitle($find_sheet_title);
        //第一sheet入职 -end

        $filename = '客户数据'.date("Y-m-d_H:i:s");
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
    }
    
    
    /*新增客户*/
    public function add()
    {
        if(request()->isAjax()){

            $data=input('post.')['data'];
            $data['aid'] = session('uid','','admin');
            $data['xaid'] = session('uid','','admin');
            $data['status'] = $data['status']?$data['status']:1;
            $data['detail'] = str_replace(PHP_EOL, '<br>', $data['detail']);
            $data['wx'] = str_replace(' ','',$data['wx']);
            // $maxCountDay = session('max_count_day','','admin')?:db('conf')->where('ename','max_count_day')->value('value');
            // $countToday = db('client')->whereTime('add_time','today')->where('aid',session('uid','','admin'))->count();
            // if($countToday >= $maxCountDay)
            // {
            //     return ['msg'=>'录入失败，超出每日最大录入数量 '.$maxCountDay,'icon'=>2];
            // }

            $unionId1 = $unionId2 = 0;

            /*if(trim($data['phone']))
            {
                $phoneRepeatInfo = db('client')->where('phone',$data['phone'])->order('id asc')->find();
                $unionId1 = $phoneRepeatInfo['union_id']?$phoneRepeatInfo['union_id']:$unionId1;
            }*/
            /*
            if(trim($data['phone[0']))
            {
                $phones = $this->getPhonesByFormData($data);

                if($phones)
                {
                    foreach ($phones as $key => $value) {
                        unset($data['phone['.$key]);
                        $phones[$key] = str_replace(' ','',$phones[$key]);
                        $phoneRepeatInfo = db('client')->where('phone','LIKE','%'.$value.'%')->whereOr('wx','LIKE','%'.$value.'%')->order('id asc')->find();
                        $unionId1 = $phoneRepeatInfo['union_id']?$phoneRepeatInfo['union_id']:$unionId1;
                        if($unionId1)
                            break;
                    }

                }
                $data['phone'] = json_encode($phones);
            }
            if(trim($data['wx'])){
                $wxRepeatInfo = db('client')->where('wx',$data['wx'])->whereOr('phone','LIKE','%'.$data['wx'].'%')->order('id asc')->find();
                $unionId2 = $wxRepeatInfo['union_id']?$wxRepeatInfo['union_id']:$unionId2;
            }
            if($unionId1 || $unionId2)
            {
                $data['union_id'] = $unionId1?$unionId1:$unionId2;
                
                $unionIds = ($unionId1 && $unionId2)?"$unionId1,$unionId2":$data['union_id'];

                $clientQdCount = db('client')->where('union_id','IN',$unionIds)->where('status',4)->count();
                
                if($clientQdCount >= 1)
                {
                    return ['msg'=>'录入失败，此客户已有有人签单','icon'=>2,'apply'=>1,'dataJson'=>json_encode($data)];
                }
                $clientGlCount = db('client')->where('union_id','IN',$unionIds)->where('status','IN','1,3')->count();
                if($clientGlCount >= 5)
                {
                    return ['msg'=>'录入失败，此客户已有5位业务员','icon'=>2,'apply'=>1,'dataJson'=>json_encode($data)];
                } 
            }
            */
           $clientRepeat = db('client')->where('union_id','IN',$unionIds)->where('status','IN','0,1,3')->where('aid',session('uid','','admin'))->find();
            if($clientRepeat)
            {
                if($clientRepeat['status'] == 0)
                {
                    db('client')->where('id',$clientRepeat['id'])->delete();
                }
                else
                    return ['msg'=>'录入失败，此客户你已有过录入','icon'=>2,'apply'=>1,'dataJson'=>json_encode($data)];
            }
            /*赛事名称判断*/
    //      $wx_client_count = db('client')->where('activity',$data['activity'])->count();
    //      if($wx_client_count >= $client_wx_limit){
    //          return ['msg'=>'该客户已被录入','icon'=>2];
    //      }

            //$data['hetong'] = $data['hetong']?'/uploads/hetong/'.$data['hetong']:'';
            if($data['status'] == 3)
            {
                $data['baoA_time'] = time();
                $data['baoA_aid'] = $data['xaid'];
            }
            if($data['status'] == 4)
            {
                $data['qiandan_time'] = time();
                $data['baoA_time'] = time();
                $data['baoA_aid'] = $data['xaid'];
            }

            $data['add_time']=time();
            $bao_A_qian_time=db('conf')->where('ename','bao_A_qian_time')->value('value');
            $data['end_time']=strtotime('+'.$bao_A_qian_time.' day');
            //添加数据到admin表，并返回id
            $add=db('client')->insert($data);
            if($add){
                return ['msg'=>'录入客户成功','icon'=>1];
            }else{
                return ['msg'=>'录入客户失败','icon'=>2];
            }
            return;
        }
        return view();
    }

    public function import()
    {
        if(request()->file('file')){
            $file = request()->file('file');
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'importexcel');
            
            //$dir= '/uploads/importexcel/'.str_replace(DS, '/', $info->getSaveName() );
            $dir = ROOT_PATH . 'public' . DS . 'uploads'.DS.'importexcel'.DS.$info->getSaveName();
            require_once(EXTEND_PATH.'/PHPExcel/Classes/PHPExcel.php');
            require_once(EXTEND_PATH.'/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php');
            $objReader = new \PHPExcel_Reader_Excel2007();
            if(!$objReader->canRead($dir))
            {
                $objReader = new \PHPExcel_Reader_Excel5();
                if(!$objReader->canRead($dir))
                {
                    echo '无法识别的Excel文件！';
                    return false;
                };
            };
            $objPHPExcel = $objReader->load($dir);        //建立excel对象

            $sheetCount = $objPHPExcel->getSheetCount();//获取sheet工作表总个数
 
            /*读取表格数据*/

            $client_wx_limit = db('conf')->where('ename','client_wx_limit')->value('value');
            $successArr = $errorArr = [];

            for($h =0;$h <=$sheetCount-1 ;$h++)//
            {//循环sheet工作表的总个数
                $currentSheet = $objPHPExcel->getSheet($h);        //**读取excel文件中的指定工作表*/
                $allColumn = $currentSheet->getHighestColumn();        //**取得最大的列号*/
                $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/
                $data = array();
                for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++)
                {        //循环读取每个单元格的内容。注意行从1开始，列从A开始
                    $i=0;
                    for($colIndex='A';$colIndex<='V';$colIndex++)
                    {
                         $addr = $colIndex.$rowIndex;
                         $cell = $currentSheet->getCell($addr)->getValue();
                         $data[$rowIndex][$i] = $cell;
                        $i++;
                    }
                }

                /*$allImage = $currentSheet->getDrawingCollection();
                $imageFilePath = './images';
                if (! file_exists ( $imageFilePath )) {
                    mkdir("$imageFilePath", 0777, true);
                }
                if($allImage){
                    foreach($allImage as $drawing){
                        //string 为有图片的表格坐标 如 A2 B3等
                        $string = $drawing->getCoordinates();
                        //获取excel中的图片
                        $filename = $drawing->getPath();
                        $img = ROOT_PATH . 'public' . DS .'images'.DS.time().'.png';
                        //这一句比较重要，将图片放在路径中
                        copy($filename, $img);
                        $cell = $currentSheet->getCell($string);echo $cell;
                        $path = $img;
                        //把图片保存的路径 丢回单元格，方便下面的保存。
                        $cell->setValue($path);
                    }
                }*/
                array_shift($data);  //删除第一个数组(标题);
                foreach ($data as $k=>$v)
                {
                    $addData = [];
                    $union_id = 0;
                    if($v[0] &&  ($v[4] || $v[5])  )
                    {

                        $addData['activity']=trim($v[0]);
                        $addData['activity_time']=trim($v[1]);
                        $addData['address']=trim($v[2]);
                        $addData['name']=trim($v[3]);
                        $addData['phone1'][0]=trim($v[4]);
                        if($addData['phone1'][0])
                            $addData['phone'] = json_encode($addData['phone1']);
                        $addData['wx']=trim($v[5]);
                        $addData['aid'] = session('uid','','admin');
                        $addData['xaid'] = session('uid','','admin');
                        $addData['status'] = 1;
                        $addData['add_time']=time();
                        $bao_A_qian_time=db('conf')->where('ename','bao_A_qian_time')->value('value');
                        $addData['end_time']=strtotime('+'.$bao_A_qian_time.' day');

                        $unionIdSel = db('client');
                        if($addData['phone1'][0])
                            $unionIdSel = $unionIdSel->where('phone','like','%'.$addData['phone1'][0].'%');
                        if($addData['wx'] && $addData['phone1'][0])
                            $unionIdSel = $unionIdSel->whereOr('wx',$addData['wx']);
                        if($addData['wx'] && !$addData['phone1'][0])
                            $unionIdSel = $unionIdSel->where('wx',$addData['wx']);
                        if($addData['wx'] || $addData['phone1'][0])
                            $union_id = $unionIdSel->order('id asc')->value('union_id');
                        if($union_id)
                            $addData['union_id'] = $union_id;
                        
                        
                        /*if($phone_client_count >= $client_wx_limit)
                        {
                            $errorArr[] = $addData;
                            continue;
                        }
    
                        $phone_client_count = db('client')->where('phone',$addData['phone'])->count();
                        if($phone_client_count >= $client_wx_limit)
                        {
                            $errorArr[] = $addData;
                            continue;
                        }
                        $wx_client_count = db('client')->where('wx',$addData['wx'])->count();
                        if($wx_client_count >= $client_wx_limit)
                        {
                            $errorArr[] = $addData;
                            continue;
                        }*/
                        $addStatus = db('client')->insert($addData);
                        
                        if($addStatus)
                        {
                            $successArr[] = $addData;
                        }
                    }

                    
                }
                
            }

            $this->assign([
                'errorArr'=>$errorArr,
                'successArr'=>$successArr
            ]);
        }

        return view();

    }


    /*编辑客户*/
    public function edit()
    {
        if(request()->isAjax()){
            $data=input('post.');
            if($data['coop_mode'])
                $data['coop_mode'] = implode(',',$data['coop_mode']);
            if(trim($data['phone[0']))
            {
                $phones = $this->getPhonesByFormData($data);
                if($phones)
                {
                    foreach ($phones as $key => $value) {
                        unset($data['phone['.$key]);
                        $phoneRepeatInfo = db('client')->where('phone','LIKE','%'.$value.'%')->where('id','<>',$data['id'])->order('id asc')->find();
                        $unionId1 = $phoneRepeatInfo['union_id']?$phoneRepeatInfo['union_id']:$unionId1;
                        if($unionId1)
                            break;
                    }

                }
                $data['phone'] = json_encode($phones);
            }
            /*if(trim($data['phone']))
            {
                $phoneRepeatInfo = db('client')->where('phone',$data['phone'])->order('id asc')->find();
                $unionId1 = $phoneRepeatInfo['union_id']?$phoneRepeatInfo['union_id']:$unionId1;
            }*/
            if(trim($data['wx'])){
                $wxRepeatInfo = db('client')->where('wx',$data['wx'])->order('id asc')->find();
                $unionId2 = $wxRepeatInfo['union_id']?$wxRepeatInfo['union_id']:$unionId2;
            }
            if($unionId1 || $unionId2)
            {
                /*$clientQdCount = db('client')->where('union_id','IN',"$unionId1,$unionId2")->where('status',4)->count();
                if($clientQdCount >= 1)
                {
                    $data['status'] = 0;
                    $msg = '此客户已有有人签单，将自动回收';
                }
                $clientGlCount = db('client')->where('union_id','IN',"$unionId1,$unionId2")->where('status','IN','1,3')->count();
                if($clientGlCount >= 5)
                {
                    $data['status'] = 0;
                    $msg = '此客户已有5位业务员，将自动回收';
                }*/
                $data['union_id'] = $unionId1?$unionId1:$unionId2;
            }
            if(!$data['hetong'])
                unset($data['hetong']);
            $data['detail'] = str_replace(PHP_EOL, '<br>', $data['detail']);
            $save=db('client')->where('id',$data['id'])->update($data);
            if($save !== false){
                $msg = $msg?$msg:'编辑客户成功';
                return ['msg'=>$msg,'icon'=>1];
            }else{
                return ['msg'=>'编辑客户失败','icon'=>2];
            }
            return;
        }
        $clients=db('client')->find(input('id'));
        $clients['phone'] = json_decode($clients['phone']);
        $this->assign([
            'clients'=>$clients,
        ]);
        return view();
    }
    public function cancelClient()
    {
        if(request()->isAjax()){
            $client_id = input('client_id');
            $aid = session('uid','','admin');
            $groupId = session('group_id','','admin');
            $clientInfo = db('client')->where('id',$client_id)->find();

            $type = input('type');
            //保A退回维护
            if($type == 2)
            {
                if($clientInfo['status'] != 3)
                {
                    return ['msg'=>'此客户不是保A状态','icon'=>2];
                }
                if($groupId == 1 || ($clientInfo['status'] == 3 && $clientInfo['xaid'] == $aid))
                {
                    $save=db('client')->where('id',$client_id)->update(['status'=>1,'baoA_aid'=>'']);
                }
                else
                {
                    return ['msg'=>'此客户不是你保A的客户','icon'=>2];
                }
            }
            //维护退回客户池
            else
            {
                if($groupId == 1 || ($clientInfo['status'] == 1 && $clientInfo['xaid'] == $aid))
                {
                    $save=db('client')->where('id',$client_id)->update(['status'=>0,'xaid'=>'']);
                    db('cancel_log')->insert(['uid'=>$clientInfo['xaid'],'client_id'=>$client_id,'add_time'=>time()]);
                }
                else
                {
                    return ['msg'=>'此客户不是你维护的客户','icon'=>2];
                }
            }
            if($save !== false){
                return ['msg'=>'操作成功','icon'=>1];
            }else{
                return ['msg'=>'操作失败','icon'=>2];
            }
            return;
        }
    }

    public function revokeClient()
    {
        if(request()->isAjax()){
            $data=input('post.')['data'];
            $data['revoke_text'] = str_replace(PHP_EOL, '<br>', $data['revoke_text']);
            $save=db('client')->update($data);
            if($save !== false){
                return ['msg'=>'操作成功','icon'=>1];
            }else{
                return ['msg'=>'操作失败','icon'=>2];
            }
            return;
        }

        $clients=db('client')->find(input('id'));
        $this->assign([
            'clients'=>$clients,
        ]);
        return view();
    }

    public function complaintClient()
    {
        if(request()->isAjax()){
            $data=input('post.')['data'];
            $data['admin_id'] = session('uid','','admin');
            $data['add_time'] = time();
            $data['content'] = str_replace(PHP_EOL, '<br>', $data['content']);
            $save=db('client_complaint')->insert($data);
            if($save !== false){
                return ['msg'=>'操作成功','icon'=>1];
            }else{
                return ['msg'=>'操作失败','icon'=>2];
            }
            return;
        }

        $clients=db('client')->find(input('id'));
        $this->assign([
            'clients'=>$clients,
        ]);
        return view();
    }

    /*保A操作*/
    public function baoA()
    {
        if(request()->isAjax()){
            $client_id = input('client_id');
            $aid = session('uid','','admin');
            $baoA_count = db('client')->where(['status'=>3,'xaid'=>$aid])->count();
            if(session('group_id','','admin') == 2)
                $bao_A_num = db('conf')->where('ename','bao_A_num')->value('value');
            else
                $bao_A_num = db('conf')->where('ename','zg_bao_A_num')->value('value');

            if($baoA_count >= $bao_A_num){
                return ['msg'=>'您已经存在'.$baoA_count.'个保A客户,达到上限。无法继续保A','icon'=>2];
            }
            $clientInfo = db('client')->where('id',$client_id)->find();
            if($clientInfo['union_id'] && $clientInfo['is_apply'] == 0)
            {
                $clientQdCount = db('client')->where('union_id',$clientInfo['union_id'])->where('status',4)->count();
                if($clientQdCount >= 1)
                {
                    return ['msg'=>'操作失败，此客户已有有人签单','icon'=>2];
                }
                $clientGlCount = db('client')->where('union_id',$clientInfo['union_id'])->where('status',3)->count();
                if($clientGlCount >= 3)
                {
                    return ['msg'=>'操作失败，此客户已有3人保A','icon'=>2];
                }
            }

            $bao_A_hou_time = db('conf')->where('ename','bao_A_hou_time')->value('value');
            $end_time = strtotime('+'.$bao_A_hou_time.' day');
            $save=db('client')->where('id',$client_id)->update(['baoA_time'=>time(),'baoA_aid'=>$admin_id,'status'=>3,'end_time'=>$end_time]);
            if($save !== false){
                return ['msg'=>'保A成功','icon'=>1];
            }else{
                return ['msg'=>'保A失败','icon'=>2];
            }
            return;
        }
    }
    /*签单操作*/
    public function qian()
    {
        if(request()->isAjax()){
            $data=input('post.');
            // print_r($data);
            // die;
            $data['end_time'] = 0;
            $data['status'] = 4;
            $data['qiandan_time'] = time();
            $data['coop_mode'] = implode(',',$data['coop_mode']);
            //$data['activity_open_time'] = strtotime($data['activity_open_time']);
            //$data['hetong'] = $data['hetong']?'/uploads/hetong/'.$data['hetong']:'';
            //print_r($data);exit;
            unset($data['file']);
            $data['hetong'] = $data['hetong']?json_encode($data['hetong']):'';
//            $clientInfo = db('client')->where('id',$client_id)->find();
            $clientInfo = db('client')->where('id',$data['id'])->find();
            if($clientInfo['union_id'])
            {
                $clientQdCount = db('client')->where('union_id',$clientInfo['union_id'])->where('status',4)->count();
                if($clientQdCount >= 1  && $clientInfo['is_apply'] == 0)
                {
                    return ['msg'=>'操作失败，此客户已有有人签单','icon'=>2];
                }
            }
            // if($data['chat_img'])
            //     $data['chat_check_status'] = -1;

            $save=db('client')->update($data);
            if($save !== false){
                return $data['chat_check_status']==-1?['msg'=>'签单成功，请等待主管审核','icon'=>1]:['msg'=>'签单成功','icon'=>1];
            }else{
                return ['msg'=>'签单失败','icon'=>2];
            }
            return;
        }

        $clients=db('client')->find(input('id'));
        $this->assign([
            'clients'=>$clients,
        ]);
        return view();
    }
    /*活动详情*/
    
    /*续期客户*/
    public function xuqi()
    {
        //print_r($_SESSION);
        if(request()->isAjax()){
            $data=input('post.')['data'];
            $data['aid'] = session('uid','','admin');
            $data['add_time'] = time();

            if($data['xuqi_id']){
                $add = db('xuqi')->where('id',$data['xuqi_id'])->update($data);
            }else{
                unset($data['xuqi_id']);
                $add=db('xuqi')->insert($data);
            }

            
            if($add){
                return ['msg'=>'申请续期提交成功','icon'=>1];
            }else{
                return ['msg'=>'申请续期提交失败','icon'=>2];
            }
            return;
        }
        $clients=db('client')->find(input('id'));
        $uid = session('uid','','admin');
        $xuqi = db('xuqi')->where('client_id',$clients['id'])->where('aid',$uid)->where('status',0)->find();
        //客户已过期
        if($clients['end_time'] < time() && $xuqi['id']){
            db('xuqi')->where('id',$xuqi['id'])->update('status',3);
        }
        $this->assign([
            'clients'=>$clients,
            'xuqi'=>$xuqi,
        ]);
        return view();
    }
    
    
    /*客户池关联客户*/
    
    public function guanlian()
    {
        if(request()->isAjax()){
            $client_id = input('client_id');
            $aid = session('uid','','admin');            
            $guanlianMaxCount = db('conf')->where('ename','guanlian_count')->value('value');
            $uid = session('uid','','admin');
            $guanlianCount = db('client')->where('xaid',$uid)->where('aid','<>',$uid)->where('status',1)->where('end_time','<',(time()+86400*7) )->where('end_time','>',(time()+86400*6) )->count();
            if($guanlianCount >= $guanlianMaxCount)
            {
                return ['msg'=>'关联失败，每日可关联'.$guanlianCount.'条','icon'=>2];
            }
            
            $clientInfo = db('client')->where('id',$client_id)->find();
            if($clientInfo['union_id'])
            {
                $clientQdCount = db('client')->where('union_id',$clientInfo['union_id'])->where('status',4)->count();
                if($clientQdCount >= 1)
                {
                    return ['msg'=>'关联失败，此客户已有有人签单','icon'=>2];
                }
                $clientGlCount = db('client')->where('union_id',$clientInfo['union_id'])->where('status','IN','1,3')->count();
                if($clientGlCount >= 5)
                {
                    return ['msg'=>'关联失败，此客户已有5位业务员','icon'=>2];
                }
            }
            /*if($clientInfo['wx'])
            {
                $clientCount2 = db('client')->where('wx',$clientInfo['wx'])->where('status','>',0)->value("GROUP_CONCAT(id SEPARATOR ',') as ids");
            }*/
            if($clientInfo['xaid'])
            {
                return ['msg'=>'该客户已被关联','icon'=>2];
            }

            $cancelCheck = db('cancel_log')->where('uid',$aid)->where('client_id',$client_id)->count();
            if($cancelCheck > 0)
            {
                return ['msg'=>'该客户属于你的回收客户','icon'=>2,'status'=>-2];
            }

            $bao_A_qian_time = db('conf')->where('ename','bao_A_qian_time')->value('value');
            $end_time = strtotime('+'.$bao_A_qian_time.' day');
            $save=db('client')->where('id',$client_id)->update(['xaid'=>$aid,'status'=>1,'end_time'=>$end_time]);
            
            if($save !== false)
            {
                return ['msg'=>'关联客户成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'关联客户失败','icon'=>2];
            }
            return;
        }
    }
    
    /*合同*/
    public function hetong(){
        $clients=db('client')->find(input('id'));
        $this->assign([
            'clients'=>$clients,
        ]);
        return view();
    }
    //layui图片上传
    public function upload(){
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(HETONGIMG);
        $data = array();  //定义一个返回的数组
        if($info){
            $reubfo['code']= 1;
            $reubfo['savename'] = str_replace("\\","/",$info->getSaveName());
        }else{
            // 上传失败获取错误信息
            $reubfo['code']= 0;
            $reubfo['err'] = $file->getError();
        } 
        return json_encode($reubfo);
    }
    //图片撤销功能 仅仅删除本地图片
    public function cancel(){
        $imgurl=input('imgurl');
        $res=@unlink(HETONGIMG.$imgurl);
    }
    
    public function getNewList($clientList)
    {
        if($clientList)
        {
            foreach ($clientList as $k => $v) 
            {
                $clientList[$k]['scount'] = getCountByClientId($v['union_id']);
            }
        }
        return $clientList;

    }
    
    
    public function qiandanRemind()
    {
        $qiandanList = db('client')->alias('c')->field('c.id,c.activity,a.name')->join('admin a','a.id=c.xaid')->where('chat_check_status','>=',-1)->where('c.qiandan_time','>',time()-86400 )->where('c.status',4)->select();
        foreach ($qiandanList as $k=>$v)
        {
            if(Cookie::get('remind_'.$v['id']) == 1)
                unset($qiandanList[$k]);
            else
                Cookie::set('remind_'.$v['id'],1,172800);
        }
        $this->assign([
            'qiandanList'=>$qiandanList
        ]);
        return view();
    }
    
    
    
    
}